package com.tongsys.server.config.security.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.tongsys.server.utils.RtnUtils;
import com.tongsys.server.utils.RtnCode;
import io.swagger.annotations.ApiModel;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
@ApiModel("登录认证失败 处理器类")
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        //设置响应编码格式
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        //获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //定义变量，保存异常信息
        String message=null;
        //判断异常类型
        if (exception instanceof AccountExpiredException){
            message="账户过期，登录失败";
        } else if (exception instanceof BadCredentialsException) {
            message="用户名密码错误，登录失败";
        } else if (exception instanceof CredentialsExpiredException) {
            message="密码过期，登录失败";
        } else if (exception instanceof DisabledException) {
            message="账户禁用，登录失败";
        } else if (exception instanceof LockedException) {
            message="账户锁定，登录失败";
        }else if (exception instanceof InternalAuthenticationServiceException){
            message="用户不存在，登录失败";
        }else {
            message="登录失败";
        }
        //将结果转换成json,消除循环引用
        String res = JSON.toJSONString(RtnUtils.err().code(RtnCode.ERROR).msg(message), SerializerFeature.DisableCircularReferenceDetect);
        //将结果集保存在输出流中 写出
        outputStream.write(res.getBytes(StandardCharsets.UTF_8));
        //刷新缓冲区，写出数据到内存
        outputStream.flush();
        //关闭流
        outputStream.close();
    }
}
